package com.yangfei.mystudy1020.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;

import com.yangfei.mystudy1020.R;
import com.yangfei.mystudy1020.utils.Network;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SocketServerActivity extends Activity {

    ServerSocket ss = null;
    private ExecutorService mThreadPool;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_socket_server);
        getPermission(this);

        mThreadPool = Executors.newCachedThreadPool();

        String ip = Network.getLocalIp(SocketServerActivity.this);
        Log.d("SocketServerActivity","ip address = "+ip);

        findViewById(R.id.connect).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startServer();
            }
        });

        findViewById(R.id.disconnect).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    int net_num = 1;
    private void startServer() {
        mThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                //创建一个ServerSocket ，监听客户端socket的连接请求
                try {
                    String ip = Network.getLocalIp(SocketServerActivity.this);

                    ss = new ServerSocket(8091, 10, InetAddress.getByName(ip));

                    Log.d("SocketServerActivity","server address = "+ss.getInetAddress());

                    while (true) {
                        Socket s = null;
                        s = ss.accept();
                        OutputStream os = s.getOutputStream();
                        String msg = "server msg"+net_num++;
                        os.write(msg.getBytes("utf-8"));
                        os.close();
                        s.close();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void getPermission(Activity act){
        if (ContextCompat.checkSelfPermission(act, Manifest.permission.ACCESS_WIFI_STATE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(act,
                    new String[]{Manifest.permission.ACCESS_WIFI_STATE},
                    11);
        }
    }
}
